package com.cms.intelligent_control.module

import android.annotation.SuppressLint
import android.app.Activity
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import com.cms.intelligent_control.R
import org.json.JSONObject

@SuppressLint("SetJavaScriptEnabled")
class BrowserModule(var activity: Activity) {

    private var mWebView: WebView = activity.findViewById(R.id.web_view)

    init {
        val setting = mWebView.settings
        setting.javaScriptEnabled = true
        mWebView.webViewClient = WebViewClient()
    }

    public fun isBrowserAction(data: JSONObject): Boolean {
        val type = data.optString("instruct_type")
        return arrayOf("浏览器控制", "软件调用", "页面跳转").contains(type)
    }

    public fun execute(data: JSONObject) {
        val type = data.optString("instruct_type")
        val name = data.optString("instruct_name")
        val operation = data.optString("exe_operation")
        when (type) {
            "浏览器控制" -> {
                if (name == "打开浏览器") {
                    mWebView.visibility = View.VISIBLE
                    mWebView.loadUrl("https://www.baidu.com/")
                } else if (name == "关闭浏览器") {
                    mWebView.loadUrl("")
                    mWebView.visibility = View.GONE
                }
            }
            "软件调用" -> {
                mWebView.visibility = View.VISIBLE
                mWebView.loadUrl(operation)
            }
            "页面跳转" -> {
                if (mWebView.visibility == View.VISIBLE) {
                    mWebView.loadUrl("javascript:$operation")
                }
            }
        }
    }

}